package com.qf.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.qf.bean.User;
import com.qf.dao.UserDao;
import com.qf.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;
    //1校验用户名是否可用
    @Override
    public Integer checkUsername(String username) {
        //健壮性判断 避免username为空串
        if(!StringUtils.isEmpty(username)){
            username = username.trim();
        }
        //调用dao查询数据条数
        Integer count = userDao.findCountByUsername(username);
        //返回数据
        return count;
    }
    //2注册账号
    @Override
    @Transactional
    public Integer register(User user) {
        //1给密码加密
        user.setPassword(new Md5Hash(user.getPassword()).toString());
        //2调用dao保存
        return userDao.save(user);
    }

    @Override
    public User login(String username, String password) {
        //1调用dao根据用户调查用户信息
        User user = userDao.findByUsername(username);
        //2判断用户名是否正确
        if(user != null){
            if(user.getPassword().equals((new Md5Hash(password).toString()))){
                //用户名和密码正确
                return user;
            }
        }
        //用户名或密码错误
        return null;
    }
}
